package com.liu.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.liu.entity.Area;
import com.liu.entity.Hospital;

import com.liu.service.AreaService;
import com.liu.service.HospitalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * (Hospital)表控制层
 *
 * @author makejava
 * @since 2023-02-08 13:01:48
 */
@RestController
@RequestMapping("/hospital")
@CrossOrigin
@Slf4j
public class HospitalController {
    /**
     * 医院对象
     */
    private HospitalService hospitalService;
    @Autowired
    @Qualifier("hospitalServiceImpl")
    public void setService(HospitalService hospitalService){
        this.hospitalService = hospitalService;
    }

    /**
     * 地区对象
     */
    private AreaService areaService;
    @Autowired
    @Qualifier("AreaServiceImpl")
    public void setService(AreaService areaService){
        this.areaService = areaService;
    }

    /**
     * 根据地区找医院
     * @param id
     * @return
     */
    @PostMapping("/findHosByProvince")
    public List<Hospital> findHosByProvince(Integer id){
        log.info("地区：{}",id);
        return hospitalService.findHosByArea(id);
    }

    /**
     * 根据id找医院
     * @param id
     * @return
     */
    @PostMapping("/findHos")
    public List<Hospital> findHos(Integer id){
        return hospitalService.findHos(id);
    }

    /**
     * 根据科室找医院
     * @param id
     * @return
     */
    @PostMapping("/findHosByDep")
    public List<Hospital> findHosByDep(Integer id){
        return hospitalService.findHosByDep(id);
    }

    /**
     * 医院总数
     * @return
     */
    @GetMapping("/count")
    public Long findCount(@RequestParam(defaultValue = "") String name,
                          @RequestParam(defaultValue = "") String type,
                          @RequestParam(defaultValue = "") String address,
                          @RequestParam(defaultValue = "") String grade) {
        return hospitalService.count(name, type,address,grade);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") String name,
                                        @RequestParam(defaultValue = "") String type,
                                        @RequestParam(defaultValue = "") String address,
                                        @RequestParam(defaultValue = "") String grade){
        pageNum = (pageNum - 1) * pageSize;
        List<Hospital> data = hospitalService.queryAllByLimit(pageNum, pageSize, name, type,address,grade);
        Long total = hospitalService.count(name, type,address,grade);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 查询全部医院
     * @return
     */
    @GetMapping("/findAll")
    public Map<String, Object> findHospital(@RequestParam(defaultValue = "") String name,
                                  @RequestParam(defaultValue = "") String type,
                                  @RequestParam(defaultValue = "") String address,
                                  @RequestParam(defaultValue = "") String grade){
        List<Hospital> data = hospitalService.findAll(name, type, address, grade);
        long count = hospitalService.count(name, type, address, grade);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",data);
        map.put("total",count);
        return map;
    }

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping("/list")
    public List<Hospital> findAll(@RequestParam(defaultValue = "") String name,
                                  @RequestParam(defaultValue = "") String type,
                                  @RequestParam(defaultValue = "") String address,
                                  @RequestParam(defaultValue = "") String grade){
        return hospitalService.findAll(name, type, address, grade);
    }

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping("/findAllArea")
    public List<Area> findAllArea(){
        return areaService.findAllArea();
    }

    /**
     * 添加或更新
     *
     * @param hospital
     */
    @PostMapping("/edit")
    public int insert(@RequestBody Hospital hospital) {
        log.info("当前保存或修改的信息:{}", hospital.toString());
        //根据传递过来的参数studentId是否存在来决定进入哪个方法
        if (hospital.getId() != null && hospital.getId().toString().length() > 0) {
            System.out.println(hospital.getId());
            return hospitalService.update(hospital);
        } else {
            System.out.println(hospital.getId());
            return hospitalService.insert(hospital);
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/del")
    public int delete(Integer id){
        log.info("当前删除数据的id:{}", id);
        return hospitalService.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delBatch")
    public int deleteBatch(@RequestBody List<Integer> ids){
        return hospitalService.deleteByIds(ids);
    }

    /**
     * 导出文件
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询所有数据
        List<Hospital> list = hospitalService.findAll("","","","");
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-utf-8");
        String fileName = URLEncoder.encode("医院信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /**
     * 导入文件
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public int  imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Hospital> list = reader.readAll(Hospital.class);
        System.out.println(list);
        return hospitalService.insertBatch(list);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @PostMapping("/findById")
    public Hospital queryById(Integer id){
        return hospitalService.queryById(id);
    }

}

